const app = getApp();
const { checkUserTelephone } = require('../util.js');
Page({
  data: {
    msgList: [],
    defaultAvatar: './img/default-avatar.png',
    page: '2', // 接口标明string
    isPoster: false,
    isMsgList: false,
    isCard: false,
    loading: true,
    isWXWork: app.isWXWork,
    isLoaded: false,
    qrCode: ''
  },

  onLoad: function (options) {
    let { openid, isPoster, isCard } = options;

    if (isPoster) {
      wx.setNavigationBarTitle({ title: '海报' });
      return this.setData({ isPoster: true });
    }
    this.setData({ openid });
    if (isCard) {
      let { cardid } = options;
      wx.setNavigationBarTitle({ title: '名片海报' });
      this.onCreateThumb(cardid);
      return this.setData({ isCard: true });
    }
    this.setData({ isMsgList: true });

    this.getMsgList({
      page: '1',
    }).then(res => {
      res.length > 0 && this.setData({
        msgList: res,
      });
    });
    app.v8_card_action_log = [];
  },

  onShow: function (argument) {
    // this.data.isMsgList &&
  },

  onUnload() {
    let data = app.v8_card_action_log;
    data instanceof Array && data.length > 0 && app.util.statRequest({
      pt: getCurrentPages().pop().route,
      pm: JSON.stringify(getCurrentPages().pop().options),
      tm: 0,
      cn: 'click',
      tp: 2,
      aa: JSON.stringify(data),
    });
    app.v8_card_action_log = [];
  },

  onCreateThumb: function (card_id) {
    let that = this;
    let openid = this.data.openid;
    let qr_path = 'common/component/universal-card/card-show';
    let module = app.siteInfo.module;
    let params = {
      card_id,
      openid,
      qr_path,
    };
    if (module === 'ws_micro_shop') {
      params.sid = app.ws_micro_shop_globalData.shopid;
    }

    app.util.request({
      url: 'card/api/create_poster',
      data: params,
      showLoading: true,
      success: function(res) {
        if (res.data.errno === 0) {
          let qrCode = res.data.data.img_url;
          that.setData({
            qrCode,
          });
        }
      },
      fail: function() {
        wx.showToast({
          title: '生成海报失败，退出重试',
          icon: 'none',
        });
      },
    });
  },

  onPullDownRefresh: function () {
    let that = this;

    if (!this.data.isMsgList) {
      wx.stopPullDownRefresh();
    } else {
      this.getMsgList({
        page: '1',
      }).then(res => {
        wx.stopPullDownRefresh();
        // && res[0].id !== msgList[0].id，可能last_content有更新过，需要重新合并。
        if (res.length > 0) {
          that.setData({
            msgList: res,
            page: '2',
          });
        } else {
          wx.showToast({
            title: '没有新会话',
            icon: 'none',
          });
        }
      }).catch(e => {
        wx.stopPullDownRefresh();
        wx.showToast({
          title: '没有新会话',
          icon: 'none',
        });
      });
    }
  },

  onLoadMore: function () {
    let that = this;
    let { msgList, page } = this.data;

    this.getMsgList({}).then(res => {
      if (res.length > 0) {
        that.setData({
          msgList: [...msgList, ...res],
          page: Number(page) + 1,
        });
      } else {
        that.setData({
          noMore: true,
        });
      }
    }).catch(e => {
      that.setData({
        noMore: true,
      });
    });
  },

  // 获取留言列表数据
  getMsgList(obj = {}) {
    let that = this;
    let { openid, page } = this.data;
    if (obj.page) page = obj.page;
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'card/api/get_session_list',
        data: {
          openid,
          page,
          pagesize: '15',
        },
        showLoading: true,
        success: function (res) {
          if (Number(res.data.errno) === 0) resolve(res.data.data);
          else reject(new Error(false));
        },
        fail: function(err) {
          reject(err);
        },
        complete: function() {
          wx.hideLoading({
            success: () => { that.setData({ loading: false }) },
          });
        },
      });
    });
  },

  gotoMsg(e) {
    // 此处fromOpenid 第一次发起会话的人；
    // to_openid，被动发起会话的人；’
    // 跳转到message对话页，语义上需要转成 fromOpenid: 发消息者 toopneid: 消息接收者
    let guestMobile = this.data.guestMobile;
    if (!guestMobile && !this.data.isWXWork) {
      checkUserTelephone.call(this, e);
    } else {
      let { mid, toOpenid, fromOpenid } = e.currentTarget.dataset;
      let currenUserOpenID = this.data.openid; // 传给message页的openID应该是当前用户的openid
      if (currenUserOpenID === fromOpenid) fromOpenid = toOpenid;

      // TODO, 处理列表未读数据 m_id
      this.clearUMsg(mid);
      let url = '/common/component/universal-card/pages/message?openid=' + currenUserOpenID + '&m_id=' + mid + '&to_openid=' + fromOpenid + '&scene=inner';
      url += '&guestMobile=' + guestMobile;
      app.util.navigateTo(url);
    }
  },

  saveQrShow: function (argument) {
    let that = this;
    let url = this.data.qrCode;
    wx.getSetting({
      success(res) {
        console.log("=======getSetting========",res)
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success(res) {
              wx.showToast({
                title: '授权成功',
              })
              that.upload(url)
            },
            fail: res =>{
              wx.showToast({
                title: '请点击右上角的设置,进行相册授权',
                icon:'none'
              })
            }
          })
        } else {
          that.upload(url)
        }
      }
    })
  },

  upload(url){
    url && wx.downloadFile({
      url,
      success: function (res) {
        if (res.statusCode === 200) {
          let filePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath,
            success: function (res) {
              wx.showToast({
                title: '保存成功',
                duration: 1500,
              });
              app.v8_card_action_log.push({
                name: 'saveQrShow',
                result: true
              });
              setTimeout(function () {
                wx.navigateBack({
                  delta: 1,
                });
              }, 1500);
            },
            fail: function (err) {
              app.v8_card_action_log.push({
                name: 'saveQrShow',
                result: false
              });
            },
          });
        }
      }
    });
  },

  clearUMsg: function (mid) {
    // let clickedMsgIndex;
    let that = this;
    this.data.msgList.forEach((item, index) => {
      if (Number(item.id) === Number(mid)) {
        let tmpKey = `msgList[${index}].n_see`;
        that.setData({
          [tmpKey]: '0',
        });
      }
    });
  },

  getUserMobile(e) {
    this.setData({ guestMobile: e.detail.mobile || '' });
  },

  onShareAppMessage: function () {
    
  }
});
